package com.xiaoxin.experience.demo;

import com.xiaoxin.experience.util.ResizeImgBase64Util;
import lombok.SneakyThrows;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author xiaoxin
 */
public class ResizeImg
{

    public static void main(String[] args) throws IOException
    {
        String src = "d:/白底证件照.png";
        String dst = "d:/out.png";
        String fileExtension = getFileExtension(src);
        try (InputStream in = Files.newInputStream(Paths.get(src));
             OutputStream out = Files.newOutputStream(Paths.get(dst))) {
            String result = ResizeImgBase64Util.resizeImage(in, 413, 626, fileExtension);
            BufferedImage image = ResizeImgBase64Util.base64String2BufferedImage(result);
            ImageIO.write(image, Objects.requireNonNull(fileExtension), out);
        }

    }

    /**
     * 图片缩放
     * @param src 图片路径
     * @param dest 缩放后图片保存路径
     * @param size 缩放后图片大小 kb
     */
    public static void resizeImg(String src, String dest, long size)
    {
        String fileExtension = getFileExtension(src);
        try (InputStream in = Files.newInputStream(Paths.get(src));
             OutputStream out = Files.newOutputStream(Paths.get(dest)))
        {
            String result = ResizeImgBase64Util.resizeImageStreamByLimit(in, size, fileExtension);
            BufferedImage image = ResizeImgBase64Util.base64String2BufferedImage(result);
            ImageIO.write(image, Objects.requireNonNull(fileExtension), out);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static String getFileExtension(String filePath)
    {
        File file = new File(filePath);

        // 获取文件名
        String name = file.getName();

        // 查找最后一个'.'字符的位置
        int lastIndexOfDot = name.lastIndexOf('.');

        // 如果没有找到'.'，或者是第一个字符就是'.'，则返回null
        if (lastIndexOfDot == -1 || lastIndexOfDot == 0) {
            return null; // 没有扩展名
        }

        // 返回扩展名
        return name.substring(lastIndexOfDot + 1);
    }
}
